package com.wct.mall.common;

import com.wct.mall.exception.ParamException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author WEI
 * @date 2020/3/22
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理参数异常
     */
    @ExceptionHandler(value = ParamException.class)
    @ResponseBody
    public JsonData paramExceptionHandler(HttpServletRequest request, ParamException e) {
        log.error("URL: {}, 参数异常！原因是：{}", request.getRequestURL(), e.getMessage());
        return JsonData.fail(e.getMessage());
    }

    /**
     * 处理空指针的异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public JsonData exceptionHandler(HttpServletRequest request, NullPointerException e) {
        log.error("URL: {}, 空指针异常！原因是: {}", request.getRequestURL(), e.getMessage());
        return JsonData.fail("500, 发生空指针异常！");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("URL: {}, 未知异常！原因是: {}, 异常类型: {}", request.getRequestURL(), e.getMessage(), e.getClass());
        return JsonData.fail("500, 服务器内部错误!");
    }
}
